package com.brave.file.service;


import com.brave.base.BaseService;
import com.brave.file.entity.MCUploadFileInfo;
import com.brave.file.repository.FileUploadRepository;
import com.brave.user.dto.RedisUserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class FileService extends BaseService
{
    //日志记录
    private static final Logger logger = LoggerFactory.getLogger(FileService.class);
    @Value("${upload.file.root.path}")
    private String fileUploadRootPath;  //上传文件本地根路径
    @Value("${upload.file.root.url}")
    private String fileUploadRootUrl;   //上传文件网络路径
    @Autowired
    private FileUploadRepository fileUploadRepository;
    
    

    /**
     * 2019年8月24日 09:18:07
     * 上传文件公用方法
     * @param file
     * @param redisUserInfo
     * @return
     */
    public String uploadFile(MultipartFile file, RedisUserInfo redisUserInfo)
    {
        try
        {
            StringBuilder fileLocalPath = new StringBuilder();
            //当前日期作为文件夹名称
            String dateFolder = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE);
            fileLocalPath.append("static").append("/").append(dateFolder).append("/");
            //公用文件资源
            fileLocalPath.append("public").append("/");
            File goalFolder = new File(fileUploadRootPath + fileLocalPath.toString());
            //目标文件夹不存在时, 需要创建
            if(!goalFolder.exists())
            {
                goalFolder.mkdirs();
            }
            String fullFileName = file.getOriginalFilename();
            String fileType = "file";
            String shortFileName = fullFileName;
            if(fullFileName.contains("."))
            {
                fileType = fullFileName.substring(fullFileName.lastIndexOf(".") + 1, fullFileName.length());
                shortFileName = fullFileName.substring(0, fullFileName.lastIndexOf("."));
            }
            //重命名文件
            StringBuilder targetFileName = new StringBuilder(UUID.randomUUID().toString());
            if(file.getOriginalFilename().contains("."))
            {
                String fileFullName = file.getOriginalFilename();
                targetFileName.append(fileFullName.substring(fileFullName.lastIndexOf("."), fileFullName.length()));
            }
            File targetFile = new File(fileUploadRootPath + fileLocalPath.toString() + targetFileName.toString());
            if(targetFile.exists())
            {
                targetFile.delete();
            }
            file.transferTo(targetFile);
            MCUploadFileInfo fileInfo = new MCUploadFileInfo();
            fileInfo.setFileName(shortFileName);
            fileInfo.setCreateDate(new Date());
            fileInfo.setComment("");
            fileInfo.setCreateUserId(redisUserInfo.getId());
            fileInfo.setFilePath(String.format("%s%s%s", fileUploadRootPath, fileLocalPath, targetFileName.toString()));
            fileInfo.setForeignId(0L);
            fileInfo.setFileType(fileType);
			fileInfo.setFileUrl(String.format("%s%s%s", fileUploadRootUrl, fileLocalPath, targetFileName.toString()));
            long fileInfoId = fileUploadRepository.save(fileInfo).getId();

            Map<String, Object> resultMap = new HashMap<>(6);
            resultMap.put("fileId", fileInfoId);
            resultMap.put("fileType", fileType);
            resultMap.put("fileName", shortFileName);
            resultMap.put("fileUrl", String.format("%s%s%s", fileUploadRootUrl, fileLocalPath, targetFileName.toString()));
            return success(resultMap);
        }catch(Exception ex)
        {
            logger.error("Exception is {}, IN {}", ex.getMessage(), "FileService.uploadFile");
            return exception(ex.getMessage());
        }
    }
    
    
    
    
    
    
    
}
